<script setup>
import { reactive, onMounted, ref } from "vue";
import { storeToRefs } from "pinia";
import useMessageStore from "@/pinia/modules/messageStore";
import BackTop from "@/components/backTop/backTop.vue";

const messageStore = useMessageStore();

const { counts, messageList } = storeToRefs(messageStore);

/*获取消息列表的分页参数*/
const params = reactive({
  contentType: 201,
  page: 1,
  pageSize: 10,
});

const scrollTop = ref(0);

const top = ref(0);

/*scroll-view组件上拉刷新的状态*/
const triggered = ref(false);

/*获取消息列表的函数*/
const fetchMessageList = async () => {
  try {
    await messageStore.fetchMessageList(params);
  } catch (error) {
    uni.showToast({ title: error.message, duration: 2000, icon: "error" });
  }
};

/*scroll-view组件下拉触底的回调函数*/
const scrolltolower = () => {
  if (messageList.value.length >= counts.value) return uni.showToast({ title: "没有更多通知", duration: 2000, icon: "error" });
  fetchMessageList();
};

/*scroll-view组件上拉刷新的回调函数*/
const refresherrefresh = async () => {
  triggered.value = true;
  params.page = 1;
  messageList.value = [];
  await fetchMessageList();
  triggered.value = false;
};


/*全部已读的回调函数*/
const handleReadAll = async () => {
  try {
    await messageStore.messageReadAll(201);
    uni.showToast({ title: "任务通知已读", duration: 2000, icon: "success" });
  } catch (error) {
    uni.showToast({ title: error.message, duration: 2000, icon: "error" });
  }
};

const goToDetail = async (contentType, message) => {
  if (message.isRead === 0) {
    await messageStore.messageRead(201, message.id);
  }
  uni.navigateTo({ url: `/subpkg_task/detail/index?id=${message.id}` });
};


const scroll = ({ detail }) => {
  scrollTop.value = detail.scrollTop;
};

onMounted(() => {
  fetchMessageList();
});

</script>

<template>
  <scroll-view class="scroll-view" refresher-enabled scroll-y show-scrollbar scroll-with-animation :scroll-top="top" @scroll="scroll" @scrolltolower="scrolltolower" @refresherrefresh="refresherrefresh" :refresher-triggered="triggered">
    <view class="scroll-view-wrapper">
      <view class="message-action">
        <text class="iconfont icon-clear"></text>
        <text @tap="handleReadAll">全部已读</text>
      </view>
      <uni-card :border="false" :is-shadow="false" v-for="(item) in messageList" :key="item.id">
        <view class="brief">{{ item.content }}</view>
        <view class="extra">
          <text class="time">{{ item.created }}</text>
          <text hover-class="none" class="link" @tap="goToDetail(201,item)">查看详情</text>
        </view>
        <template v-slot:title>
          <view class="title" :class="{unread:!item.isRead}">您有新的运输任务</view>
        </template>
      </uni-card>
      <view class="message-blank" v-if="!messageList.length">暂无消息</view>
      <back-top :show="scrollTop>=700" @click="top=Math.random()"></back-top>
    </view>
  </scroll-view>
</template>

<style lang="scss" scoped>
@import './styles.scss';
</style>
